<template>
  <div class="projects-manager">
    <!-- 项目经历列表 -->
    <div class="projects-list">
      <div v-if="loading" class="loading-text">加载中...</div>
      <div v-else-if="projects.length === 0" class="empty-text">暂无项目经历</div>
      <ul v-else class="experience-list">
        <li v-for="project in projects" :key="project.id" class="project-item">
          <!-- 项目信息 -->
          <div class="project-content">
            <span class="project-name">{{ project.projectName }}</span>
            <span v-if="hasExtraInfo(project)" class="project-extra">
              （{{ formatExtraInfo(project) }}）
            </span>
            <div v-if="project.projectUrl" class="project-url">
              项目链接：<a :href="project.projectUrl" target="_blank" class="url-link">{{ project.projectUrl }}</a>
            </div>
          </div>
          
          <!-- 操作按钮 -->
          <div class="project-actions">
            <button @click="editProject(project)" class="action-btn edit-btn" title="编辑">✏️</button>
            <button @click="confirmDeleteProject(project)" class="action-btn delete-btn" title="删除">🗑️</button>
          </div>
        </li>
      </ul>
    </div>

    <!-- 添加按钮 -->
    <div class="add-button-container">
      <button @click="addProject" class="add-btn">
        <span class="add-icon">+</span>
        添加项目经历
      </button>
    </div>

    <!-- 添加/编辑项目经历弹窗 -->
    <div v-if="showProjectModal" class="modal-overlay" @click="closeProjectModal">
      <div class="modal-content project-modal" @click.stop>
        <div class="modal-header">
          <h3>{{ isEditing ? '编辑项目经历' : '添加项目经历' }}</h3>
          <button class="close-btn" @click="closeProjectModal">×</button>
        </div>
        <div class="modal-body">
          <form class="project-form">
            <div class="form-group">
              <label>项目名称 <span class="required">*</span></label>
              <input 
                v-model="projectForm.projectName" 
                type="text" 
                class="form-input"
                placeholder="请输入项目名称"
                maxlength="200"
              />
            </div>
            <div class="form-group">
              <label>项目角色</label>
              <input 
                v-model="projectForm.projectRole" 
                type="text" 
                class="form-input"
                placeholder="请输入项目角色，如：项目经理、开发者、前端工程师等"
                maxlength="100"
              />
            </div>
            <div class="form-row">
              <div class="form-group half-width">
                <label>开始时间</label>
                <input 
                  v-model="projectForm.startTime" 
                  type="date" 
                  class="form-input"
                />
              </div>
              <div class="form-group half-width">
                <label>结束时间</label>
                <input 
                  v-model="projectForm.endTime" 
                  type="date" 
                  class="form-input"
                />
              </div>
            </div>
            <div class="form-group">
              <label>使用技术</label>
              <input 
                v-model="projectForm.technologiesUsed" 
                type="text" 
                class="form-input"
                placeholder="请输入使用的技术栈，如：Vue.js, Java, MySQL等"
                maxlength="500"
              />
            </div>
            <div class="form-group">
              <label>项目链接</label>
              <input 
                v-model="projectForm.projectUrl" 
                type="url" 
                class="form-input"
                placeholder="请输入项目链接或演示地址"
                maxlength="500"
              />
            </div>
            <div class="form-group">
              <label>项目描述</label>
              <textarea 
                v-model="projectForm.projectDescription" 
                class="form-textarea"
                placeholder="请描述项目的相关情况（可选）"
                maxlength="500"
              ></textarea>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeProjectModal" :disabled="saving">取消</button>
          <button class="confirm-btn" @click="saveProject" :disabled="saving">
            {{ saving ? '保存中...' : '保存' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div v-if="showDeleteModal" class="modal-overlay" @click="closeDeleteModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>确认删除</h3>
          <button class="close-btn" @click="closeDeleteModal">×</button>
        </div>
        <div class="modal-body">
          <div class="icon-wrapper">
            <div class="warning-icon">⚠️</div>
          </div>
          <p class="modal-text">确定要删除这个项目经历吗？</p>
          <p class="modal-subtitle">「{{ deleteTarget?.projectName }}」</p>
          <p class="modal-hint">删除后无法恢复</p>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeDeleteModal" :disabled="deleting">取消</button>
          <button class="confirm-btn delete-confirm" @click="deleteProject" :disabled="deleting">
            {{ deleting ? '删除中...' : '确认删除' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 消息提示弹窗 -->
    <div v-if="showMessageModal" class="modal-overlay" @click="closeMessageModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header" :class="messageType === 'success' ? 'success-header' : 'error-header'">
          <h3>{{ messageTitle }}</h3>
          <button class="close-btn" @click="closeMessageModal">×</button>
        </div>
        <div class="modal-body">
          <div class="icon-wrapper">
            <div class="message-icon" :class="messageType === 'success' ? 'success-icon' : 'error-icon'">
              {{ messageType === 'success' ? '✓' : '✗' }}
            </div>
          </div>
          <p class="modal-text">{{ messageText }}</p>
        </div>
        <div class="modal-footer">
          <button class="confirm-btn" @click="closeMessageModal">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { 
  getStudentProjectsService, 
  addStudentProjectService, 
  updateStudentProjectService, 
  deleteStudentProjectService 
} from '@/api/student.js'

// 数据状态
const projects = ref([])
const loading = ref(false)

// 添加/编辑弹窗状态
const showProjectModal = ref(false)
const isEditing = ref(false)
const currentProjectId = ref(null)
const saving = ref(false)
const projectForm = ref({
  projectName: '',
  projectRole: '',
  startTime: '',
  endTime: '',
  technologiesUsed: '',
  projectUrl: '',
  projectDescription: ''
})

// 删除弹窗状态
const showDeleteModal = ref(false)
const deleteTarget = ref(null)
const deleting = ref(false)

// 消息提示弹窗状态
const showMessageModal = ref(false)
const messageTitle = ref('')
const messageText = ref('')
const messageType = ref('success')

// 组件挂载时加载数据
onMounted(() => {
  fetchProjects()
})

// 获取项目经历列表
const fetchProjects = async () => {
  loading.value = true
  try {
    const result = await getStudentProjectsService()
    if (result.code === 200) {
      projects.value = result.data || []
    } else {
      console.error('获取项目经历失败:', result.msg)
      projects.value = []
    }
  } catch (error) {
    console.error('获取项目经历异常:', error)
    projects.value = []
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 格式化时间段
const formatTimeRange = (startTime, endTime) => {
  const start = formatDate(startTime)
  const end = formatDate(endTime)
  
  if (start && end) {
    return `${start}至${end}`
  } else if (start) {
    return start
  } else if (end) {
    return end
  }
  return ''
}

// 检查是否有额外信息
const hasExtraInfo = (project) => {
  return project.projectRole || 
         project.startTime || 
         project.endTime || 
         project.technologiesUsed
}

// 格式化额外信息
const formatExtraInfo = (project) => {
  const parts = []
  
  if (project.projectRole) {
    parts.push(project.projectRole)
  }
  
  const timeRange = formatTimeRange(project.startTime, project.endTime)
  if (timeRange) {
    parts.push(timeRange)
  }
  
  if (project.technologiesUsed) {
    parts.push(`技术栈：${project.technologiesUsed}`)
  }
  
  return parts.join('，')
}

// 添加项目经历
const addProject = () => {
  isEditing.value = false
  currentProjectId.value = null
  projectForm.value = {
    projectName: '',
    projectRole: '',
    startTime: '',
    endTime: '',
    technologiesUsed: '',
    projectUrl: '',
    projectDescription: ''
  }
  showProjectModal.value = true
}

// 编辑项目经历
const editProject = (project) => {
  isEditing.value = true
  currentProjectId.value = project.id
  projectForm.value = {
    projectName: project.projectName || '',
    projectRole: project.projectRole || '',
    startTime: project.startTime || '',
    endTime: project.endTime || '',
    technologiesUsed: project.technologiesUsed || '',
    projectUrl: project.projectUrl || '',
    projectDescription: project.projectDescription || ''
  }
  showProjectModal.value = true
}

// 关闭添加/编辑弹窗
const closeProjectModal = () => {
  showProjectModal.value = false
  projectForm.value = {
    projectName: '',
    projectRole: '',
    startTime: '',
    endTime: '',
    technologiesUsed: '',
    projectUrl: '',
    projectDescription: ''
  }
}

// 保存项目经历
const saveProject = async () => {
  if (!projectForm.value.projectName.trim()) {
    showErrorMessage('请输入项目名称')
    return
  }

  saving.value = true
  try {
    let result
    if (isEditing.value) {
      // 编辑模式
      result = await updateStudentProjectService(currentProjectId.value, {
        id: currentProjectId.value,
        ...projectForm.value
      })
    } else {
      // 添加模式
      result = await addStudentProjectService(projectForm.value)
    }

    if (result.code === 200) {
      closeProjectModal()
      await fetchProjects() // 重新加载数据
      showSuccessMessage(isEditing.value ? '项目经历更新成功' : '项目经历添加成功')
    } else {
      showErrorMessage(result.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存项目经历异常:', error)
    let errorMessage = '保存项目经历时发生错误，请稍后重试'
    
    if (error && error.code && error.msg) {
      errorMessage = error.msg
    } else if (error && error.response && error.response.data && error.response.data.msg) {
      errorMessage = error.response.data.msg
    }
    
    showErrorMessage(errorMessage)
  } finally {
    saving.value = false
  }
}

// 确认删除项目经历
const confirmDeleteProject = (project) => {
  deleteTarget.value = project
  showDeleteModal.value = true
}

// 关闭删除确认弹窗
const closeDeleteModal = () => {
  showDeleteModal.value = false
  deleteTarget.value = null
}

// 删除项目经历
const deleteProject = async () => {
  if (!deleteTarget.value) return
  
  deleting.value = true
  try {
    const result = await deleteStudentProjectService(deleteTarget.value.id)
    if (result.code === 200) {
      closeDeleteModal()
      await fetchProjects() // 重新加载数据
      showSuccessMessage('项目经历删除成功')
    } else {
      showErrorMessage(result.msg || '删除失败')
    }
  } catch (error) {
    console.error('删除项目经历异常:', error)
    showErrorMessage('删除项目经历时发生错误，请稍后重试')
  } finally {
    deleting.value = false
  }
}

// 显示成功消息
const showSuccessMessage = (text) => {
  messageType.value = 'success'
  messageTitle.value = '操作成功'
  messageText.value = text
  showMessageModal.value = true
}

// 显示错误消息
const showErrorMessage = (text) => {
  messageType.value = 'error'
  messageTitle.value = '操作失败'
  messageText.value = text
  showMessageModal.value = true
}

// 关闭消息弹窗
const closeMessageModal = () => {
  showMessageModal.value = false
}
</script>

<style scoped>
/* 主容器 */
.projects-manager {
  max-width: 800px;
  margin: 0 auto;
}

/* 项目经历列表 */
.projects-list {
  margin-bottom: 30px;
}

.loading-text, .empty-text {
  text-align: center;
  color: #999;
  padding: 40px 20px;
  font-size: 16px;
}

.experience-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.project-item {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.project-item:last-child {
  border-bottom: none;
}

.project-content {
  flex: 1;
  margin-right: 15px;
}

.project-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  display: block;
  margin-bottom: 5px;
}

.project-extra {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
  display: block;
  margin-bottom: 5px;
}

.project-url {
  font-size: 12px;
  color: #888;
  margin-top: 5px;
}

.url-link {
  color: #667eea;
  text-decoration: none;
  word-break: break-all;
}

.url-link:hover {
  text-decoration: underline;
}

.project-actions {
  display: flex;
  gap: 5px;
  flex-shrink: 0;
}

.action-btn {
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  transition: all 0.2s ease;
}

.edit-btn {
  background: #e3f2fd;
  color: #1976d2;
}

.edit-btn:hover {
  background: #bbdefb;
}

.delete-btn {
  background: #ffebee;
  color: #d32f2f;
}

.delete-btn:hover {
  background: #ffcdd2;
}

/* 添加按钮 */
.add-button-container {
  text-align: center;
}

.add-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.add-icon {
  font-size: 18px;
  font-weight: bold;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.modal-content {
  background: white;
  border-radius: 15px;
  max-width: 500px;
  width: 100%;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.modal-header {
  padding: 20px 20px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 20px;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.success-header h3 {
  color: #4caf50;
}

.error-header h3 {
  color: #f44336;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background: #f5f5f5;
  color: #666;
}

.modal-body {
  padding: 0 20px 20px;
}

.project-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-row {
  display: flex;
  gap: 15px;
}

.half-width {
  flex: 1;
}

.form-group label {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.required {
  color: #f44336;
}

.form-input, .form-textarea {
  padding: 12px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.2s ease;
  font-family: inherit;
}

.form-input:focus, .form-textarea:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-textarea {
  min-height: 100px;
  resize: vertical;
}

.modal-footer {
  padding: 0 20px 20px;
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.cancel-btn, .confirm-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  min-width: 80px;
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
}

.cancel-btn:hover:not(:disabled) {
  background: #e0e0e0;
}

.confirm-btn {
  background: #667eea;
  color: white;
}

.confirm-btn:hover:not(:disabled) {
  background: #5a67d8;
}

.confirm-btn:disabled, .cancel-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.delete-confirm {
  background: #f44336;
}

.delete-confirm:hover:not(:disabled) {
  background: #d32f2f;
}

/* 消息弹窗特殊样式 */
.icon-wrapper {
  text-align: center;
  margin-bottom: 15px;
}

.warning-icon, .message-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.success-icon {
  color: #4caf50;
}

.error-icon {
  color: #f44336;
}

.modal-text {
  text-align: center;
  font-size: 16px;
  color: #333;
  margin: 0 0 10px 0;
}

.modal-subtitle {
  text-align: center;
  font-size: 14px;
  color: #667eea;
  font-weight: 600;
  margin: 0 0 10px 0;
}

.modal-hint {
  text-align: center;
  font-size: 12px;
  color: #999;
  margin: 0;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .modal-overlay {
    padding: 10px;
  }
  
  .project-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .project-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .modal-content {
    max-height: 95vh;
  }
  
  .form-row {
    flex-direction: column;
    gap: 20px;
  }
}
</style>


